import { defineComponent, ref, PropType, Ref, nextTick, isRef, unref} from "vue";
import ChooseTeamDialog from '@src/modules/setting/task/taskTypeSetting/manage/components/ChooseTeamDialog.vue'
import { FunctionComponent } from "@src/util/types";
import { i18n } from '@src/locales';
import './styles/style.scss'
import { TypeMappingFormTypeValueName, FormItemType } from './model/enum'
import { FormTypeValueNameKey,FormItem, FormItemProps, ShowModalParams, TagItem } from './model/interface'
import { uniqBy } from 'lodash'

const FORM_ITEM_ARR: Array<FormItem> = [{
    label: i18n.t('task.setting.taskTypeSetting.manage.canCreateDept') as unknown as string,
    type: 'create',
    checkedIdArr: ref([]),
    checkedIdNodeArr: ref([]),
    requestParams: ref({})

}, {
    label: i18n.t('task.setting.taskTypeSetting.manage.canCheckDept') as unknown as string,
    type: 'check',
    checkedIdArr: ref([]),
    checkedIdNodeArr: ref([]),
    requestParams: ref({})
}]

export default defineComponent({
    name: 'choose-team-confirm-dialog',
    components: {
        [ChooseTeamDialog.name]: ChooseTeamDialog
    },
    props: {
        type: {
            type: String as PropType<string>,
            default: ''
        }
    },
    setup(props, { emit, expose }) {
        const { type } = props
        // const { emit, expose } = ctx
        const modalVisible = ref(false)
        const isShowChooseTeamModal = ref(false)
        const currentFormItemType = ref<FormTypeValueNameKey>('create')
        const currentItemId = ref('')

        /**
         * 描述 弹窗保存事件
         * @date 2023-02-14
         * @returns {any}
         */
        const handleSubmit = () => {
            emit('submit',  { value: FORM_ITEM_ARR, id: currentItemId.value })
            close()
        }  

        /**
         * 描述 关闭弹窗
         * @date 2023-02-14
         * @returns {any}
         */
        const close = () => {
            modalVisible.value = false
        }

        /**
         * 描述 弹窗
         * @date 2023-02-14
         * @param {any} params:ShowModalParams
         * @returns {any}
         */
        const showModal = (params: ShowModalParams)=> {
            currentItemId.value = params.id
            FORM_ITEM_ARR.map(item=> item.type).forEach((type: FormTypeValueNameKey) => {
                orderFormTypeSetValues(type, params)
            })
            modalVisible.value = true
        }

        /**
         * 描述 根据type设置对应的值
         * @date 2023-02-14
         * @param {any} type:FormTypeValueNameKey
         * @param {any} params:ShowModalParams
         * @returns {any}
         */
        const orderFormTypeSetValues = (type: FormTypeValueNameKey, params: ShowModalParams) => {
            const currentUpdateItem = orderFormItemTypeFindItem(type)
            currentUpdateItem.checkedIdArr.value = params[TypeMappingFormTypeValueName[type]].map((item: TagItem) => item.id) as unknown as Array<never>
            currentUpdateItem.checkedIdNodeArr.value = params[TypeMappingFormTypeValueName[type]] as unknown as Array<never>
        }
        /**
         * 描述 根据FORM_ITEM_ARR item的type找对应的item
         * @date 2023-02-14
         * @param {any} type?:string
         * @returns {any}
         */
        const orderFormItemTypeFindItem = (type?: string) => {
            const currentUpdateItem = FORM_ITEM_ARR.find(item=> item.type === (type ? type : currentFormItemType.value)) as unknown as FormItem
            return currentUpdateItem
        }

        /**
         * 描述 选择部门后的回调更新值
         * @date 2023-02-14 
         * @param {any} value:Record<string
         * @param {any} any>
         * @returns {any}
         */
        const handleUpdateTeamList = (value: Record< string, any>)=> {
            const { checkedTeamList, checkedTeamObjList, requestParams } = value

            /**
             * 描述 判断更新的数据与当前的数据长度
             * @date 2023-03-30
             * @param {any} updateValue=[]
             * @param {any} currentValue=[]
             * @returns {any}
             */
            const checkUpdateOverCurrent = (updateValue = [], currentValue = []) => {
                return updateValue.length > currentValue.length
            }

            /**
             * 描述 更新数据
             * @date 2023-03-30
             * @param {any} type:FormTypeValueNameKey
             * @returns {any}
             */
            const updateValue = (type: FormTypeValueNameKey) => {
                const currentUpdateItem = orderFormItemTypeFindItem(type)
                currentUpdateItem.checkedIdArr.value = checkUpdateOverCurrent(checkedTeamList, currentUpdateItem.checkedIdArr.value) ? [...new Set([...currentUpdateItem.checkedIdArr.value, ...checkedTeamList])] as unknown as never[] : checkedTeamList

                //赋值默认有值的情况 然后并且去重处理
                currentUpdateItem.checkedIdNodeArr.value = checkUpdateOverCurrent(checkedTeamObjList, currentUpdateItem.checkedIdNodeArr.value) ? uniqBy([...currentUpdateItem.checkedIdNodeArr.value, ...checkedTeamObjList], 'id') as unknown as never[] : checkedTeamObjList
                
                if(currentUpdateItem?.requestParams) {
                    currentUpdateItem.requestParams.value = requestParams
                }
            }

            currentFormItemType.value === FormItemType.Create ?
                FORM_ITEM_ARR.map(item=> item.type).forEach((type: FormTypeValueNameKey) => updateValue(type))
                :
                updateValue(currentFormItemType.value)
        }

        /**
         * 描述 方法组件 --渲染可创建可以查看的dom
         * @date 2023-02-14
         * @param {any} ctx:FunctionComponent
         * @returns {any}
         */
        const DeptCheckFormItem = (ctx: FunctionComponent) => {
            const { item, type } = ctx.props as unknown as FormItemProps
            const nodeArr = item.checkedIdNodeArr.value
            /**
             * 描述 点击对应item弹出对应选择部门弹窗
             * @date 2023-02-14
             * @returns {any}
             */
            const handleItemChooseDept = () => {
                currentFormItemType.value = type
                setTimeout(()=> isShowChooseTeamModal.value = true, 100)
            }

            /**
             * 描述 单个tag item的清除操作
             * @date 2023-02-14
             * @param {any} e:Event
             * @param {any} item:Record<string
             * @param {any} any>
             * @returns {any}
             */
            const handleTagItemClose = (e: Event, item: Record<string, any>) => {
                e.stopPropagation()
                const currentUpdateItem = orderFormItemTypeFindItem(type)
                currentUpdateItem.checkedIdArr.value = currentUpdateItem.checkedIdArr.value.filter(checkedItem => checkedItem !== item.id)
                currentUpdateItem.checkedIdNodeArr.value = currentUpdateItem.checkedIdNodeArr.value.filter((checkedItem: Record<string, any>) => checkedItem.id !== item.id)
            }
    
            /**
             * 描述 清空所有选中
             * @date 2023-02-14
             * @param {any} e:Event
             * @param {any} type:string
             * @returns {any}
             */
            const hanldeClearAll = (e: Event, type: string) => {
                e.stopPropagation()
                const currentUpdateItem = orderFormItemTypeFindItem(type)
                currentUpdateItem.checkedIdArr.value = []
                currentUpdateItem.checkedIdNodeArr.value = []
            }

            return (
                <div class="dept-form-use__item" onClick={handleItemChooseDept}>
                <label>{item.label} { type ===  FormItemType.Check ? <el-tooltip class="item" effect="dark" content={i18n.t('task.setting.taskTypeSetting.manage.title12')} placement="top"><i class="iconfont icon-question-circle"></i></el-tooltip> : null} </label>
                <div class="dept-form-use__content">
                    <div class="dept-form-use__content-list">
                        { nodeArr.length > 0 ? nodeArr.map((item: Record<string, any>) => {
                            return (
                                <div class="dept-choose-tag">
                                    <span>{item.tagName}</span>
                                    <i class="el-icon-close" onClick={(e)=> handleTagItemClose(e, item)}></i>
                                </div>
                            )
                        }) : (
                            <span class="dept-form-use__placeholder">{i18n.t('task.setting.taskTypeSetting.manage.allTeam')}</span>
                        )}
                    </div>
                    <i class={["icon-suffix", nodeArr.length === 0 ? "el-icon-arrow-down" : "el-icon-circle-close"]} onClick={(e)=> hanldeClearAll(e, type)}></i>
                </div>
            </div>
            )
        }

        expose({
            showModal
          });
        
        return ()=>  (
            <base-modal
                title={i18n.t('task.setting.taskTypeSetting.manage.title11')}
                show={modalVisible.value}
                width="470px"
                mask-closeable={false}
                {...{ on: {['update:show']: (val: boolean) => modalVisible.value = val }}}>
                <div class="dept-form-use">
                    {FORM_ITEM_ARR.map((item: FormItem)=> {
                        // @ts-ignore
                        return <DeptCheckFormItem item={item} type={item.type}/>
                    })}
                </div>
                <div slot="footer" class="dialog-footer">
                    <el-button onClick={close}>{i18n.t('common.base.cancel')}</el-button>
                    <el-button type="primary" onClick={handleSubmit}>{i18n.t('common.base.save')}</el-button>
                </div>
                <choose-team-dialog
                    type={type}
                    id={currentItemId.value}
                    visiable={isShowChooseTeamModal.value}
                    nodeArr={orderFormItemTypeFindItem()?.checkedIdNodeArr.value || []}
                    value={orderFormItemTypeFindItem()?.checkedIdArr.value || []}
                    onUpdate={handleUpdateTeamList}
                    {...{ on:{ ['update:visiable']: (val: boolean) => isShowChooseTeamModal.value = val} }}
                 />
          
            </base-modal>
        )
    }
})